package com.kylin.common.core.util;

import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;

import java.io.IOException;
import java.util.Map;

public class HttpClient5Utils {

    private static final int MAX_TOTAL_CONNECTIONS = 200; // 最大连接数
    private static final int MAX_PER_ROUTE_CONNECTIONS = 100; // 每个路由最大连接数
    private static final int SOCKET_TIMEOUT_MS = 5000; // 套接字超时时间，单位：毫秒
    private static final int CONNECT_TIMEOUT_MS = 100; // 连接超时时间，单位：毫秒

    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
        connManager.setDefaultMaxPerRoute(MAX_PER_ROUTE_CONNECTIONS);

        // 设置超时时间
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(Timeout.ofMilliseconds(CONNECT_TIMEOUT_MS))
                .setResponseTimeout(Timeout.ofMilliseconds(CONNECT_TIMEOUT_MS)).build();
        httpClient = HttpClients.custom().setDefaultRequestConfig(config).setConnectionManager(connManager).build();

    }

    /**
     * 发送 GET 请求
     * @param url 请求的 URL
     * @param headers 请求头，可为 null
     * @return 响应内容
     * @throws IOException 请求异常
     * @throws ClientProtocolException 请求异常
     */
    public static String get(String url, Map<String, String> headers) throws IOException, ClientProtocolException {
        long start = System.currentTimeMillis();
        HttpGet httpGet = new HttpGet(url);
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(httpGet::addHeader);
        }
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectionRequestTimeout(Timeout.ofMilliseconds(100))
//                .setResponseTimeout(Timeout.ofMilliseconds(100))
//                .build();
//        httpGet.setConfig(requestConfig);
        String response = httpClient.execute(httpGet, new BasicHttpClientResponseHandler());
        System.out.println("====>" + (System.currentTimeMillis() - start));
        return response;
    }

    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        String result = get("https://helper-api-40215-8-1317557797.sh.run.tcloudbase.com/ai/ask/list", null);
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(result);
    }
}

